import { closeDB, getDB } from "@/utils/db";
import { newId } from "@/utils/id";
import { err, ok } from "@/utils/resp";

export async function GET(
  _: Request,
  { params: { id } }: { params: { id: string } }
) {
  try {
    const db = await getDB();
    const node: SubmeNode | undefined = await db.get(
      `SELECT id, "type", name, host, port, password, "path" FROM nodes WHERE id=?`,
      id
    );
    if (!node) {
      throw new Error("不存在的记录");
    }
    await closeDB();
    return ok(node!);
  } catch (e) {
    return err(e as Error);
  }
}
export async function DELETE(
  _: Request,
  { params: { id } }: { params: { id: string } }
) {
  try {
    const db = await getDB();
    const r = await db.run("DELETE FROM nodes WHERE id=?", id);
    await closeDB();
    return ok({ id, aff: r.changes });
  } catch (e) {
    return err(e as Error);
  }
}
export async function POST(
  _: Request,
  { params: { id } }: { params: { id: string } }
) {
  try {
    const db = await getDB();
    const node: SubmeNode | undefined = await db.get(
      `SELECT id, "type", name, host, port, password, "path" FROM nodes WHERE id=?`,
      id
    );
    if (!node) {
      throw new Error("不存在的记录");
    }
    const nid = newId();
    const name = `${nid}#${node.name}`.substring(0, 255);
    const newNode: SubmeNode = { ...node, name, id: nid };
    await db.run(
      `INSERT INTO nodes (id, "type", name, host, port, password, "path") VALUES(?,?,?,?,?,?,?)`,
      newNode.id!,
      newNode.type,
      newNode.name,
      newNode.host,
      newNode.port,
      newNode.password,
      newNode.path
    );
    await closeDB();
    return ok(newNode);
  } catch (e) {
    return err(e as Error);
  }
}
